package iredis

import (
	"gitee.com/tietang/terrace-go/v2/base"
	"github.com/go-redis/redis/v8"
	log "github.com/sirupsen/logrus"
	"github.com/tietang/props/v3/kvs"
)

var redisClient *redis.Client

func GetRedisClient() *redis.Client {
	base.Check(redisClient)
	return redisClient
}

func Rdb() *redis.Client {
	return GetRedisClient()
}

func initRedisClient(conf kvs.ConfigSource) *redis.Client {
	opts := &redis.Options{
		//Addr:     conf.GetDefault("redis.addr", "127.0.0.1:6379"),
		//Password: conf.GetDefault("redis.password", ""),
		//DB:       conf.GetIntDefault("redis.database", 0),
		//PoolSize: conf.GetIntDefault("redis.poolSize", 3),
	}
	err := kvs.Unmarshal(conf, opts, "redis")
	if err != nil {
		panic(err)
	}
	log.Infof("connecting redis: %+v", opts)
	redisClient = redis.NewClient(opts)
	log.Info("connected redis:", redisClient.String())
	return redisClient
}

type RedisStarter struct {
	base.BaseStarter
}

func (s *RedisStarter) Init(ctx base.StarterContext) {
	initRedisClient(ctx.Props())
	ctx["redis"] = redisClient
}
func (s *RedisStarter) Setup(ctx base.StarterContext) {
}
